package org.finesys.common.security.authentication.handler;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.finesys.common.core.util.WebUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 表单登录失败处理逻辑
 */
@Slf4j
public class FormAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (log.isDebugEnabled()) {
            log.debug("表单登录失败：{}", exception.getLocalizedMessage());
        }
        String contextPath = request.getContextPath();
        String url = HttpUtil.encodeParams(String.format("%s/token/login?error=%s", contextPath, exception.getMessage()), CharsetUtil.CHARSET_UTF_8);
        try {
            WebUtils.getResponse().sendRedirect(url);
        } catch (IOException e) {
            log.error("重定向失败", e);
        }
    }
}
